import request from "@/utils/request.ts";
import {refreshUserAnonymous, userAnonymous} from "@/apis/user_api.ts";

export function updateToken(token: string): void {
    localStorage.setItem('token', token)
}

export function clearToken(): void {
    localStorage.removeItem('token')
}

export function updateUid(uid: string): void {
    localStorage.setItem('uid', uid)
}

export function toJSON<T>(data: any): T {
    return JSON.parse(data.toString()) as T
}

export function fixPageDTO<T>(page: CommonPageReqDTO<T>): CommonPageReqDTO<T> {
    if (page.page <= 0) {
        page.page = 1
    }
    if (page.pageSize <= 0) {
        page.pageSize = 10
    } else if (page.pageSize > 100) {
        page.pageSize = 100
    }
    return page
}

async function jwtCheck(): Promise<boolean> {
    const res = await request.post(`/jwt/check`) as CommonResDTO<number>
    return res.data === 1
}

export async function checkTokenValid(): Promise<boolean> {
    let validate = await jwtCheck()
    if (!validate) {
        clearToken()
        // alert('请先登录')
        validate = await signByAnonymous() // 游客登录
    }
    if (!validate) {
        alert('请清除浏览器缓存后重试')
    }
    return validate
}

async function signByAnonymous(): Promise<boolean> {
    const uid = localStorage.getItem('uid')
    if (uid) {
        await refreshUserAnonymous(uid)
    } else {
        await userAnonymous()
    }
    return await jwtCheck()
}

export interface CommonResDTO<T> {
    code: number
    message: string
    data?: T
}

export interface CommonPageReqDTO<T> {
    page: number
    pageSize: number
    data?: T
}

export interface CommonPageResDTO<T> {
    page: number
    pageSize: number
    totalCount: number
    list: T[]
}